<template>
  <div class="min-icon" @click="showChatBox">
    <el-badge is-dot class="item">
      <el-image class="icon-pic" :src="ChatIcon" :style="{
        filter: !onlineState?'grayscale(100%)':''
      }"/>
    </el-badge>
  </div>
</template>

<script lang="ts">
import {defineComponent, ref, onMounted, getCurrentInstance} from 'vue';
import ChatIcon from "/@/assets/chat/chat-server.svg";
import {useUserInfo} from "/@/stores/userInfo";
import WebSocketWrapper from "/@/utils/wsUtil"
import {useSound} from '@vueuse/sound'
import NoticeMisc from "/@/assets/chat/5c892a36da55f4814.mp3"


export default defineComponent({
  name: 'ChatMainMini',
  props: {
    value: {
      type: String,
      default: () => '',
    },
  },
  setup(props) {
    const {play} = useSound(NoticeMisc, {
      interrupt: true,
      autoplay: true
    })
    const {proxy} = <any>getCurrentInstance();
    const onlineState = ref(false);
    const ws = ref<WebSocketWrapper>();
    const userStores = useUserInfo();
    const showChatBox = async () => {
      await userStores.setChatMaxState(true)
      await userStores.setChatMinState(true)
      // 延迟推送当前连接状态
      setTimeout(() => {
        proxy.mittBus.emit("wsMessage", Object.assign({}, {type: 'state', value: onlineState.value}));
      }, 100)
    }
    const onMessage = (data: any) => {
      if (data.type == 'pong') {
        onlineState.value = true;
        proxy.mittBus.emit("wsMessage", Object.assign({}, {type: 'state', value: onlineState.value}));
      } else {
        proxy.mittBus.emit("wsMessage", Object.assign({}, data));
        if (data.data.uid != userStores.userInfos.hash) {
          play();
        }
      }
    };

    onMounted(() => {
      const _uid = userStores.userInfos.hash;
      ws.value = new WebSocketWrapper('wss://im.wocoding.cn/wsim?uid=' + _uid, {
        maxReconnectAttempts: 10,
        reconnectDelay: 3000,
        heartbeatInterval: 15000
      });
      ws.value.on('open', () => {
        onlineState.value = true;
        proxy.mittBus.emit("wsMessage", Object.assign({}, {type: 'state', value: onlineState.value}));
      });
      ws.value.on('close', () => {
        onlineState.value = false;
        proxy.mittBus.emit("wsMessage", Object.assign({}, {type: 'state', value: onlineState.value}));
      });
      ws.value.on('message', (data: any) => {
        onMessage(data)
      });
      proxy.mittBus.on('wsSend', (data: any) => {
        if (ws.value) {
          ws.value.send({type: 'msg', data: data})
        }
      })
    })
    return {
      onlineState,
      ChatIcon,
      showChatBox,
    };
  },
});
</script>

<style scoped lang="scss">
.min-icon {
  cursor: pointer;
  width: 40px;
  height: 40px;
  position: absolute;
  right: 20px;
  bottom: 20px;
  z-index: 1999;
}
</style>
